<template>
  <div class="page-container custom-container">
    <card :title="`自驾${templateSort == 1 ? '短租' : '长租'}车型价格`" :showDivider="false">
      <page-form :model="form" ref="formRef" :rules="rules" layout="vertical">
        <!-- 系统模板 -->
        <page-form-row v-if="templateType == 1">
          <page-form-item style="margin-bottom: 0" field="templateName" label="模板名称" required>
            <i-input disabled v-model="form.templateName" :max-length="20" />
          </page-form-item>
          <page-form-item style="margin-bottom: 0" field="status" label="模板状态" required>
            <a-select disabled placeholder="请选择" v-model="form.status" allow-clear>
              <a-option v-for="item in dict.statusMap" :key="item.value" :label="item.label" :value="item.value" />
            </a-select>
          </page-form-item>
          <!-- 系统模板 应用门店 固定值为全部 -->
          <page-form-item style="margin-bottom: 0" label="应用门店" required>
            <a-input default-value="全部" disabled>
              <template #suffix>
                <icon-down />
              </template>
            </a-input>
          </page-form-item>
        </page-form-row>
        <!-- 自定义模板 -->
        <template v-if="templateType == 2">
          <page-form-row>
            <page-form-item field="templateName" label="模板名称" required>
              <i-input v-model="form.templateName" :max-length="20" />
            </page-form-item>
            <page-form-item field="status" label="模板状态" required>
              <a-select placeholder="请选择" v-model="form.status" allow-clear>
                <a-option v-for="item in dict.statusMap" :key="item.value" :label="item.label" :value="item.value" />
              </a-select>
            </page-form-item>
          </page-form-row>
          <page-form-row>
            <page-form-item style="margin-bottom: 0" field="siteIdList" label="应用门店" required size="2/3">
              <fast-transfer
                style="width: 100%"
                :titles="['未配置门店', '已选中门店']"
                v-model="form.siteIdList"
                :data-source="siteList"
                :selected-list="selectedList"
                @change="onSiteChoice"
              />
            </page-form-item>
          </page-form-row>
        </template>
        <a-divider :style="{ margin: '20px 0' }" />
        <!-- 短租配置 -->
        <sorderConfig ref="sorderConfigRef" v-if="templateSort == 1" @batchPriceSettingSuccess="handleBatchPriceSettingSuccess" />
        <!-- 长租配置 -->
        <lorderConfig ref="lorderConfigRef" v-if="templateSort == 2" />
      </page-form>
    </card>
    <page-form-footer :ok-loading="okLoading" @ok="submitFn" />
  </div>
</template>

<script setup name="CarModelPriceForm">
  import { ref, reactive, provide, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  import { usePageDict } from '@/hooks/useDict'
  import { getTemplateRelateSiteList, getTemplateDetail, getTemplateModelInfos, saveTemplate, editTemplate } from '@/api/business/price.js'
  import useNavigate from '@/hooks/useNavigate'
  import bus from '@/utils/bus'
  // 短长租配置
  import sorderConfig from './components/sorder-config.vue'
  import lorderConfig from './components/lorder-config.vue'
  const { navigateBack, replaceTo } = useNavigate()
  const dict = usePageDict('tenantPriceDict')
  const route = useRoute()
  const _query = route.query
  const _params = route.params
  const isCreate = route.name == 'CarModelPriceForm_Create'
  // 模板类型是短租、还是长租
  const templateSort = isCreate ? _params.templateSort : _query.templateSort
  const formRef = ref(null)
  provide('formRef', formRef)
  const selectedList = ref([])
  const form = reactive({
    status: 1, // 默认启用
    templateSort: templateSort,
    tenantPriceModelList: [],
  })
  provide('form', form)
  // 门店列表（会排除其他模板中的id，包含当前模板包含的门店id以及其他未被关联过的门店id）
  const siteList = ref([])
  const getSiteLIst = async (param = {}) => {
    const res = await getTemplateRelateSiteList(param)
    const result = res.result
    if (result?.length > 0) {
      siteList.value = result.map((item) => {
        return {
          label: item.siteName,
          value: item.siteId || item.id,
        }
      })
    }
  }
  // form Rules
  const rules = ref({
    templateName: { required: true, message: '请输入模板名称' },
    siteIdList: { required: true, message: '请选择应用门店', trigger: 'change' },
  })

  // 模板类型 自定义类型
  const templateType = ref(2)
  // 编辑
  let templateId = _params.id

  // 门店选择逻辑
  const sorderConfigRef = ref(null)
  const lorderConfigRef = ref(null)
  const onSiteChoice = () => {
    const param = {
      id: form.id,
      siteIdList: form.siteIdList,
      templateSort,
    }
    getTemplateModelInfos(param).then((res) => {
      const list = res.result || []
      if (templateSort == 1) sorderConfigRef.value.updateTableList(list, 'siteChoice')
      if (templateSort == 2) lorderConfigRef.value.updateTableList(list, 'siteChoice')
    })
  }

  const okLoading = ref(false)
  // 模板保存
  const submitFn = (noticeSuccess) => {
    formRef.value.validate((error) => {
      if (!error) {
        okLoading.value = true
        // 编辑
        let api = saveTemplate
        if (form.id) {
          api = editTemplate
        }
        api(form)
          .then((res) => {
            // 新增模板
            if (!form.id) {
              const priceModuleId = res.result
              console.log('priceModuleId', priceModuleId)
              noticeSuccess()
              navigateBack()

              // 派发消息到列表页，告知创建成功
              bus.emit('priceCarModelCreateSuccess')
              // 跳转新页面
              replaceTo(
                `/car-model-price/edit/${priceModuleId}?templateType=${templateType.value}&templateSort=${templateSort}`,
                `${form.templateName}-编辑`
              )
            } else {
              noticeSuccess()
              navigateBack()
            }
          })
          .finally(() => {
            okLoading.value = false
          })
      }
    })
  }

  // 获取详情
  const getDetail = (callback, type = 'getDetail') => {
    // 模板详情
    getTemplateDetail({ id: form.id }).then((res) => {
      const result = res.result
      // 已关联门店列表
      const tenantPriceSiteList = result.tenantPriceSiteList || []

      // 处理 form 数据 开始
      form.id = templateId
      form.status = result.status
      form.templateName = result.templateName
      // 自定义模板 siteIdList 传 null
      form.siteIdList = templateType.value == 2 ? tenantPriceSiteList.map((item) => item.siteId) : null
      // 处理 form 数据 结束
      // 更新车型数据
      if (templateSort == 1) sorderConfigRef.value.updateTableList(result.tenantPriceModelList, type)
      if (templateSort == 2) lorderConfigRef.value.updateTableList(result.tenantPriceModelList, type)

      callback && callback()
    })
  }

  // 短租批量设置回调
  const handleBatchPriceSettingSuccess = () => {
    getDetail()
  }

  onMounted(() => {
    // 存在模板id，编辑模板
    if (templateId) {
      // 模板类型
      templateType.value = _query.templateType
      // 模板详情
      // 处理 form 数据 开始
      form.id = templateId
      getDetail(() => {
        // 自定义模板
        if (_query.templateType == 2) {
          // 获取门店未关联列表
          getSiteLIst({ id: templateId, templateSort: templateSort }).then(() => {
            selectedList.value = []
          })
        }
      })
    } else {
      // 获取门店未关联列表
      getSiteLIst({ templateSort: templateSort })
    }
  })
</script>

<style lang="less" scoped>
  .custom-container {
    padding-bottom: 0;
  }
</style>
